package com.yyysj.friend.service.Impl;

import com.yyysj.common.core.constants.Constants;
import com.yyysj.common.core.enums.ResultCode;
import com.yyysj.common.core.utils.ThreadLocalUtils;
import com.yyysj.common.security.exception.ServiceException;
import com.yyysj.friend.domain.po.Post;
import com.yyysj.friend.domain.po.Comment;
import com.yyysj.friend.mapper.CommentMapper;
import com.yyysj.friend.mapper.PostMapper;
import com.yyysj.friend.service.ICommentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class CommentServiceImpl implements ICommentService {

    private final CommentMapper commentMapper;
    private final PostMapper postMapper;

    @Override
    public String add(Long postId, String content) {
        // 1. 根据帖子id判断帖子是否存在
        Post post = postMapper.selectById(postId);
        log.info("帖子: {}", post);
        if(post == null) {
            throw new ServiceException(ResultCode.POST_NOT_EXISTS);
        }

        // 2. 添加评论
        Comment comment = new Comment();

        Long userId = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        comment.setUserId(userId);

        comment.setPostId(postId);
        comment.setContent(content);
        log.info("评论: {}", comment);

        int rows = commentMapper.insert(comment);
        if(rows < 1) {
            throw new ServiceException(ResultCode.FAILED);
        }

        return content;
    }
}
